﻿using System;
using System.Net.Sockets;
using BingoClientModel;
using BingoServerCommon.Common;
using HPSocketCS;
using TcpClient = HPSocketCS.TcpClient;

namespace _TestClient
{
	public partial class Client 
    {

        private delegate void ConnectUpdateUiDelegate();
        private delegate void SetAppStateDelegate(AppState state);

        void ConnectUpdateUi()
        {
            if (checkBoxAsyncConn.Checked == true)
            {
                //SetAppState(AppState.Started);
            }
        }



        HandleResult OnPrepareConnect(TcpClient sender, IntPtr socket)
        {
            return HandleResult.Ok;
        }

        HandleResult OnConnect(TcpClient sender)
        {
            // 已连接 到达一次

            // 如果是异步联接,更新界面状态
            Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));

            AddMsg($" > [{sender.ConnectionId},OnConnect]");

            return HandleResult.Ok;
        }

        HandleResult OnSend(HPSocketCS.TcpClient sender, byte[] bytes)
        {
            // 客户端发数据了
            AddMsg($" > [{sender.ConnectionId},OnSend] -> ({bytes.Length} bytes)");

            return HandleResult.Ok;
        }

        HandleResult OnReceive(TcpClient sender, byte[] bytes)
        {
            // 数据到达了
            int id = NetFunction.ntoh(BitConverter.ToInt32(bytes, 0));
            Package pack = PackageFactory.Instance.NewPackage((short)id, bytes);
			//pack.Excute();
			

            AddMsg($" > [{sender.ConnectionId},OnReceive] -> ({bytes.Length} bytes) -> {((EnumPackCommand)id).ToString()}");

	        var result = HandleResult.Ok;
			return result;
        }

        HandleResult OnClose(TcpClient sender, SocketOperation enOperation, int errorCode)
        {
            if (errorCode == 0)
                // 连接关闭了
                AddMsg($" > [{sender.ConnectionId},OnClose]");
            else
                // 出错了
                AddMsg($" > [{sender.ConnectionId},OnError] -> OP:{enOperation},CODE:{errorCode}");

            // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
            // 生产环境请自己控制
           // this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);

            return HandleResult.Ok;
        }





        /// <summary>
        /// 往listbox加一条项目
        /// </summary>
        /// <param name="msg"></param>
        public void AddMsg(string msg)
        {
            if (listBoxMessage.InvokeRequired)
            {
                // 很帅的调自己
                listBoxMessage.Invoke(AddMsgDelegate, msg);
            }
            else
            {
                if (listBoxMessage.Items.Count > 100)
                {
                    listBoxMessage.Items.RemoveAt(0);
                }
                listBoxMessage.Items.Add(msg);
                listBoxMessage.TopIndex = listBoxMessage.Items.Count - (int)(listBoxMessage.Height / listBoxMessage.ItemHeight);
            }
        }

    }
}
